#pragma once

#include<iostream>
#include<pthread.h>
#include<vector>
#include<string>
#include<queue>
#include<unistd.h>
#include"Task.hpp"

using namespace std;

struct ThreadInfo
{
    pthread_t tid;
    string name;
};

const int defaultnum = 5;

template<class T>
class ThreadPool
{
public:
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }

    void Unlock()
    {
        pthread_mutex_unlock(&_mutex);
    }

    void Wakeup()
    {
        pthread_cond_signal(&_cond);
    }

    void ThreadSleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }

    bool IsQueueEmpty()
    {
        return _tasks.empty();
    }

    string ToString(pthread_t tid)
    {
        for(const auto &t: _threads)
        {
            if(t.tid == tid)
                return t.name;
        }
        return "null";
    }
public:
    ThreadPool(int num = defaultnum)
    :_threads(num)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

    static void *HandlerTask(void * args)
    {
        //?
        ThreadPool<T> *tp = static_cast<ThreadPool<T> *>(args);
        while(true)
        {
            // sleep(1);
            // cout<<"wait a new task"<<endl;
            tp->Lock();
            while(tp->IsQueueEmpty())
            {
                tp->ThreadSleep();
            }
            Task t = tp->Pop();
            tp->Unlock();
            t();
            cout<<"result: "<<t.GetResult()<<endl;
        }
    }

    void Start()
    {
        int num = _threads.size();
        for(int i = 0; i< num; i++)
        {
            _threads[i].name = "thread-" + to_string(i + 1);
            pthread_create(&(_threads[i].tid), nullptr, HandlerTask, this);
        }
    }

    void Push(const T& t)
    {
        Lock();
        _tasks.push(t);
        Wakeup();
        Unlock();
    }

    T Pop()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }
private:
    vector<ThreadInfo> _threads;
    queue<T> _tasks;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;
};